package cn.jee.controller;

import cn.jee.entity.Student;
import cn.jee.entity.Teacher;
import cn.jee.repository.StudentRepository;
import cn.jee.repository.TeacherRepository;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/students")
public class StudentController {
    
    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
    
    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private TeacherRepository teacherRepository;
    
    @GetMapping("/new")
    public String showCreateForm(Model model) {
        logger.debug("显示新建学生表单");
        model.addAttribute("student", new Student());
        return "student/create";
    }
    
    @PostMapping("/")
    public String create(@Valid @ModelAttribute Student student, BindingResult result) {
        logger.debug("创建新学生: {}", student.getName());
        if (result.hasErrors()) {
            logger.error("学生数据验证失败: {}", result.getAllErrors());
            return "student/create";
        }
        studentRepository.save(student);
        return "redirect:/teachers/";
    }
    
    @GetMapping("/assign/{teacherId}")
    public String showAssignPage(@PathVariable Long teacherId, Model model) {
        logger.debug("显示教师[{}]的学生分配页面", teacherId);
        Teacher teacher = teacherRepository.findById(teacherId)
            .orElseThrow(() -> new RuntimeException("教师不存在"));
        model.addAttribute("teacher", teacher);
        model.addAttribute("assignedStudents", studentRepository.findByTeacherId(teacherId));
        model.addAttribute("unassignedStudents", studentRepository.findByTeacherIsNull());
        return "student/assign";
    }
    
    @GetMapping("/assign/{teacherId}/{studentId}")
    public String assignStudent(@PathVariable Long teacherId, @PathVariable Long studentId) {
        logger.debug("分配学生[{}]给教师[{}]", studentId, teacherId);
        Teacher teacher = teacherRepository.findById(teacherId)
            .orElseThrow(() -> new RuntimeException("教师不存在"));
        Student student = studentRepository.findById(studentId)
            .orElseThrow(() -> new RuntimeException("学生不存在"));
        student.setTeacher(teacher);
        studentRepository.save(student);
        return "redirect:/students/assign/" + teacherId;
    }
    
    @GetMapping("/upload/{studentId}")
    public String showUploadForm(@PathVariable Long studentId, Model model) {
        logger.debug("显示学生[{}]的头像上传页面", studentId);
        Student student = studentRepository.findById(studentId)
            .orElseThrow(() -> new RuntimeException("学生不存在"));
        model.addAttribute("studentId", studentId);
        return "student/upload";
    }
    
    @PostMapping("/upload/{studentId}")
    public String uploadPhoto(@PathVariable Long studentId, @RequestParam("photo") MultipartFile photo) throws IOException {
        logger.debug("上传学生[{}]的头像", studentId);
        Student student = studentRepository.findById(studentId)
            .orElseThrow(() -> new RuntimeException("学生不存在"));
            
        if (!photo.isEmpty()) {
            String fileName = photo.getOriginalFilename();
            logger.debug("保存头像文件: {}", fileName);
            File dest = new File("d:/" + fileName);
            photo.transferTo(dest);
            
            student.setPhoto(fileName);
            studentRepository.save(student);
        }
        
        if (student.getTeacher() != null) {
            return "redirect:/students/assign/" + student.getTeacher().getId();
        }
        return "redirect:/teachers/";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Long id) {
        logger.debug("删除学生[{}]", id);
        studentRepository.deleteById(id);
        return "redirect:/teachers/";
    }
    
    @ExceptionHandler({RuntimeException.class, IOException.class})
    @ResponseBody
    public String handleException(Exception e) {
        logger.error("发生错误: ", e);
        return "操作失败：" + e.getMessage();
    }
} 